$("#uploaderCompress").uploader({
  autoUpload: false,
  url: "",
  previewImageSize: { width: 350, height: 350 },
  fileTemplate: "<div></div>",
  multi_selection: true,
  filters: {
    mime_types: [{ title: "图片", extensions: "jpg,png,gif,jpeg,bmp" }],
    max_file_size: "300mb",
  },
});

var uploaderCompress = $("#uploaderCompress").data("zui.uploader");
let imgLitsData = [];
$("#uploaderCompress")
  .uploader()
  .on("onFilesAdded", async function (files) {
    imgLitsData = [];
    // if (uploaderCompress.getFiles().length > 1) {
    //     uploaderCompress.removeFile(uploaderCompress.getFiles()[0]);
    //     // $('#range').prop('value', '0')
    // }
    // var file = uploaderCompress.getFiles()[0].getNative();
    var fileList = uploaderCompress.getFiles();
    var q = 1 - $("#range").val() / 100;
    // const newFileList = _.cloneDeep(fileList);
    // 深拷贝文件对象
    var newFileList = fileList.map((file) => {
      // 创建一个新的Blob对象，它包含与原始文件相同的数据
      var newBlob = file.getNative().slice(0, file.getNative().size, file.getNative().type);
      // 使用新的Blob创建一个新的File对象
      return new File([newBlob], file.getNative().name, { type: file.getNative().type });
    });

    $("#compressBtn").button("loading");
    $("#range").off("change");
    // 压缩图片
    // for (const item of newFileList) {
    //   const data = await lrzimgList(item.getNative(), q);
    //   imgLits.push(data);
    // }
    const promises = newFileList.map((item) => lrzimgList(item, q));
    const imgLits = await Promise.all(promises);
    // console.log(imgLits);
    imgLitsData = imgLits;
    $("#imageContainer").empty();
    for (const item of imgLits) {
      setUp(item);
    }
    while (fileList.length > 0) {
      uploaderCompress.removeFile(uploaderCompress.getFiles()[0]);
    }
    $("#compressBtn").button("reset");
    $("#content").show();
    // 更新压缩图片率
    $("#range").on("change", async function () {
      $("#rv").text($(this).val() + "%");
      console.log(123);

      var q = 1 - $("#range").val() / 100;
      imgLitsData = [];
      const promises = newFileList.map((item) =>
        lrzimgList(item, q)
      );
      const imgLits = await Promise.all(promises);
      imgLitsData = imgLits;
      $("#imageContainer").empty();
      for (const item of imgLits) {
        setUp(item);
      }
    });
  });

const setUp = (item) => {
  let div = document.createElement("div");
  div.className = "img_box";
  div.innerHTML = `
        <div class="img_not">源文件：<span class="textNot">${item.sourceSize}KB</span></div>
        <div class="img_not">压缩后传输大小：<span class="textOk">${item.resultSize}KB （省${item.scale}%）</span></div>
        <div class="img_Img">
            <a class="aImgLink" href="${item.str}" download="${item.name}">
              <img src="${item.str}" alt="">
            </a>
        </div>
    `;
  $("#imageContainer").append(div);
};

$("#range").on("change", function () {
  $("#rv").text($(this).val() + "%");
});

// $('#downloadPicss').click(function(){
//     console.log('imgLits');
// })

$("#downloadPicsss").on("click", function () {
  let $button = $(this);
  $button.button("loading");
  imgLitsData.forEach((item) => {
    let a = $("<a>", {
      href: item.str,
      download: item.name,
      style: "display:none",
    }).appendTo("body");
    a[0].click();
    a.remove();
  });
  imgLitsData = [];
  $button.button("reset");
});

function toFixed2(num) {
  return parseFloat(+num.toFixed(2));
}
function lrzimgList(file, q) {
  return new Promise((resolve, reject) => {
    lrz(file, {
      quality: q,
    }).then(function (rst) {
      let sourceSizes = toFixed2(file.size / 1024);
      let resultSizes = toFixed2(rst.fileLen / 1024);
      let scales = parseInt(100 - (resultSizes / sourceSizes) * 100);
      let name = file.name;
      const data = {
        rst,
        sourceSize: sourceSizes, // 初始大小
        resultSize: resultSizes, // 压缩后大小
        scale: scales, // 压缩率
        name,
        str: rst.base64,
      };
      resolve(data);
      reject("压缩失败");
    });
  });
}
function lrzimg(file) {
  var q = 1 - $("#range").val() / 100;
  lrz(file, {
    quality: q,
  }).then(function (rst) {
    var img = new Image(),
      div = document.createElement("div"),
      p = document.createElement("p"),
      p2 = document.createElement("p"),
      p3 = document.createElement("p"),
      a = document.createElement("a"),
      sourceSize = toFixed2(file.size / 1024),
      resultSize = toFixed2(rst.fileLen / 1024),
      scale = parseInt(100 - (resultSize / sourceSize) * 100);
    p.innerHTML =
      '源文件：<span class="text-danger">' + sourceSize + "KB" + "</span>";
    p2.innerHTML =
      '压缩后传输大小：<span class="text-success">' +
      resultSize +
      "KB (省" +
      scale +
      "%)" +
      "</span> ";
    p3.innerHTML = "默认压缩率为60%，请自行调整标尺修改图片压缩率";
    p3.style.border = "none";
    p3.style.marginLeft = "20px";
    a.className = "btn";
    a.innerHTML = "下载压缩图片";
    $("body").off("click", "#info1 a");
    $("body").on("click", "#info1 a", function () {
      base64ToBolbAndDownload(rst.base64, file.name);
    });
    div.appendChild(img);
    $("#info1").html("");
    $("#info1").append(p).append(p2).append(a).append(p3);
    $("#zigeer").show();
    img.onload = function () {
      $("#content").html("");
      document.querySelector("#content").appendChild(div);
    };

    img.src = rst.base64;
    $("#compressBtn").button("reset");
    $("#content").show();
    return rst;
  });
}

/**
 *
 * @param obj
 * @returns {String}
 * @example
 *
 */
String.prototype.render = function (obj) {
  var str = this,
    reg;
  Object.keys(obj).forEach(function (v) {
    reg = new RegExp("\\!\\{" + v + "\\}", "g");
    str = str.replace(reg, obj[v]);
  });

  return str;
};

/**
 *
 * @param element
 * @param event
 * @returns {boolean}
 */
function fireEvent(element, event) {
  var evt;

  if (document.createEventObject) {
    // IE浏览器支持fireEvent方法
    evt = document.createEventObject();
    return element.fireEvent("on" + event, evt);
  } else {
    // 其他标准浏览器使用dispatchEvent方法
    evt = document.createEvent("HTMLEvents");
    // initEvent接受3个参数：
    // 事件类型，是否冒泡，是否阻止浏览器的默认行为
    evt.initEvent(event, true, true);
    return !element.dispatchEvent(evt);
  }
}
